import 'package:audioplayers/audioplayers.dart';

class PlayHelper {
  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isPlaying = false;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;

  void setupAudioPlayer(Function(bool, Duration, Duration) onStateChanged) {
    _audioPlayer.onDurationChanged.listen((Duration d) {
      _duration = d;
      onStateChanged(_isPlaying, _position, _duration);
    });

    _audioPlayer.onPositionChanged.listen((Duration p) {
      _position = p;
      onStateChanged(_isPlaying, _position, _duration);
    });

    _audioPlayer.onPlayerComplete.listen((_) {
      _isPlaying = false;
      _position = Duration.zero;
      onStateChanged(_isPlaying, _position, _duration);
    });
  }

  Future<bool> playPause(String audioPath) async {
    if (_isPlaying) {
      await _audioPlayer.pause();
    } else {
      await _audioPlayer.play(DeviceFileSource(audioPath));
    }
    _isPlaying = !_isPlaying;
    return _isPlaying;
  }

  void setSource(String path) {
    _audioPlayer.setSourceDeviceFile(path);
  }

  void dispose() {
    _audioPlayer.dispose();
  }

  double _speed = 1.0; // 初始播放速度为1.0

  Future<void> setSpeed(double speed) async {
    _speed = speed;
    if (_audioPlayer.state == PlayerState.playing) {
      await _audioPlayer.setPlaybackRate(_speed);
    }
  }
}
